// 计算合并单元格的信息
export const mergeCells = (data, key) => {
  const mergeMap = {}
  data.forEach((item, index) => {
    const value = item[key]
    if (index === 0 || value !== data[index - 1][key]) {
      mergeMap[value] = { index, count: 1, firstIndex: item.index }
    } else {
      mergeMap[value].count += 1
    }
  })
  return mergeMap
}

// 获取带有合并信息的列配置
export const getMergedColumns = (columns, data) => {
  return columns.map((column) => {
    if (!column.merge) {
      return column
    }
    const mergeMap = mergeCells(data, column.dataIndex)
    return {
      ...column,
      customCell: (record, rowIndex) => {
        const cellValue = record[column.dataIndex]
        const mergeInfo = mergeMap[cellValue]
        if (mergeInfo.index === rowIndex) {
          return { rowSpan: mergeInfo.count }
        }
        return { rowSpan: 0 }
      },
    }
  })
}

// 按照 name 列合并情况调整 index 列
export const calculateIndexColumn = (data, mergeKey) => {
    let currentIndex = 1
    return data.reduce((acc, curr, i) => {
      if (i > 0 && curr[mergeKey] === acc[i - 1][mergeKey]) {
        curr.index = acc[i - 1].index;
      } else {
        curr.index = currentIndex++;
      }
      acc.push(curr)
      return acc;
    }, [])
  }
